﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace TST.SharePointObjects
{
    internal class SiteColumnList : SiteObjectList
    {
        public SiteColumnList(LicensingMode licensingMode, SPSite site, SPWeb web, Guid farmID, SharePointObjectsDatabase database)
            : base(licensingMode, site, web, farmID, database)
        {
        }

        protected override void doLoadFromWeb()
        {
            foreach (SPField field in Web.Fields)
            {
                SiteObject obj = new SiteObject(field.Id.ToString("B"), field.InternalName, SiteObjectType.SiteColumn);
                Add(obj);
            }
        }

        protected override void doLoadFromWeb(string groupFilter, string nameSearch)
        {
            foreach (SPField field in Web.Fields)
            {
                if ((string.IsNullOrEmpty(groupFilter) || string.Compare(field.Group, groupFilter, true) == 0) &&
                   (string.IsNullOrEmpty(nameSearch) || field.Title.ToLower().Contains(nameSearch.ToLower())))
                {
                    string title = field.Title;
                    if (string.Compare(title, field.InternalName, true) != 0)
                    {
                        title += string.Format(" ({0})", field.InternalName);
                    }
                    SiteObject obj = new SiteObject(field.Id.ToString("B"), title, SiteObjectType.SiteColumn);
                    obj.Group = field.Group;
                    obj.Url = string.Format("{0}/_layouts/fldedit.aspx?field={1}", Web.Url, field.InternalName);
                    Add(obj);
                }
            }
        }

        public override SiteObjectType SiteObjectType
        {
            get
            {
                return SiteObjectType.SiteColumn;
            }
        }

        internal static bool IsSiteColumn(SPWeb web, SPField listField)
        {
            foreach (SPField field in web.AvailableFields)
            {
                if (field.Id == listField.Id)
                {
                    return true;
                }
            }
            return false;
        }

    }
}
